﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using JetBrains.Annotations;

namespace StreetPacMan.FrontEnd.Infra
{
    public class JsonSerializer
    {
        public static string SerializeToString(object obj)
        {
            byte[] temp = SerializeToBytes(obj);
            return Encoding.UTF8.GetString(temp);
        }

        [NotNull]
        private static byte[] SerializeToBytes(object obj)
        {
            using (var temp = SerializeToStream(obj))
            {
                var length = (int)temp.Length;
                var bytes = new byte[length];
                temp.Read(bytes, 0, length);
                return bytes;
            }
        }

        private static MemoryStream SerializeToStream(object obj)
        {
            var serializer = new DataContractJsonSerializer(obj.GetType());
            var body = new MemoryStream();
            serializer.WriteObject(body, obj);
            body.Flush();
            body.Position = 0;
            return body;
        }
    }
}